package 多线程和队列.锁;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用lock interrupted中断
 *
 * @author 孔令富  2021/12/25
 */
public class LockInterruptDemo implements Runnable {

    public static void main(String[] args) throws InterruptedException {
        LockInterruptDemo interruptDemo = new LockInterruptDemo();

        Thread t1 = new Thread(interruptDemo);
        Thread t2 = new Thread(interruptDemo);

        t1.start();
        t2.start();
        TimeUnit.SECONDS.sleep(3);
        t2.interrupt();
        System.out.println("结束");
    }

    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        try {
            lock.lockInterruptibly();
            while (true) {
                Thread.yield();
            }
        } catch (InterruptedException exception) {
            exception.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
